package nettyexample.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import nettyexample.command.Packet;
import nettyexample.command.PacketCodeC;
import nettyexample.entity.LoginRequestPacket;
import nettyexample.entity.LoginResponsetPacket;

/**
 * @author zoush
 * @time 2024/12/18 10:19
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(io.netty.channel.ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf requestByteBuf = (ByteBuf) msg;

        Packet packet = PacketCodeC.INSTANCE.decode(requestByteBuf);
        if (packet instanceof LoginRequestPacket) {
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
            LoginResponsetPacket loginResponsePacket=new LoginResponsetPacket();
            loginResponsePacket.setVersion(packet.getVersion());
            if ("username".equals(loginRequestPacket.getUsername())&& "pwd".equals(loginRequestPacket.getPassword())){
                // 校验成功
                loginResponsePacket.setSuccess(true);
                System.out.println("客户端登录成功！");
            }else {
                // 校验失败
                loginResponsePacket.setReason("账号或密码错误");
                loginResponsePacket.setSuccess(false);
                System.out.println("客户端登录失败！");
            }
            // 编码，结果发送给客户端
            ByteBuf encode = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
            ctx.channel().writeAndFlush(encode);
        }


    }


}
